package system

import (
	"context"
	"strconv"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListMenuLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	menuModel model.SysMenuModel
}

func NewListMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListMenuLogic {
	return &ListMenuLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
	}
}

func (l *ListMenuLogic) ListMenu(req *types.ListMenuRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel, l.ctx, "system:menu:query")
	if err != nil {
		return nil, err
	}
	roleIds, err := auth.GetRoleIds(l.ctx)
	if err != nil {
		return nil, err
	}
	isAdmin, err := auth.IsAdmin(l.ctx)
	if err != nil {
		return nil, err
	}
	var menudtos []*model.SysMenu
	if !isAdmin {
		menudtos, err = l.menuModel.GetListByRoleIds(l.ctx, nil, roleIds)
	} else {
		menudtos, err = l.menuModel.GetListByRoleIds(l.ctx, nil, nil)
	}
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}
	var menuVos []*types.Menu
	for _, val := range menudtos {
		menuVos = append(menuVos, &types.Menu{
			MenuId:    val.MenuId,
			MenuName:  val.MenuName,
			ParentId:  strconv.Itoa(int(val.ParentId)),
			OrderNum:  val.OrderNum,
			Path:      val.Path,
			Component: val.Component.String,
			MenuType:  val.MenuType,
			Visible:   val.Visible,
			Status:    val.Status,
			Perms:     val.Perms.String,
			Icon:      val.Icon,
		})
	}
	menuVo := menuSort(menuVos)
	return &types.CommonResponse{
		Status: 500,
		Msg:    "查询成功",
		Data:   menuVo,
	}, nil
}
